package com.xcl.exception;

import com.xcl.pojo.Result;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

@RestControllerAdvice   //这个注解表示当前这个类是一个全局异常处理器类
public class GlobalExceptionHandler {

    //捕获及处理参数校验失败的异常
    @ExceptionHandler(MethodArgumentNotValidException.class) // 捕获数据校验失败的异常
    public Result handleArgumentException(MethodArgumentNotValidException e){
        String errorMsg = e.getBindingResult().getFieldErrors().stream()
                .map(fieldError -> fieldError.getDefaultMessage()).collect(Collectors.joining());
        return Result.error(errorMsg);

    }


    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e){
        e.printStackTrace();
        return Result.error(StringUtils.hasLength(e.getMessage()) ?e.getMessage():"服务器异常!");
    }





}
